<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\Area;
use think\exception\ValidateException;
use app\common\model\Address as AddressModel;
use app\common\tool\Result;
use think\response\Json;

class Address extends Base
{
    /**
     * 地址列表
     */
    public function getList()
    {
        try {
            $map = ['uid' => $this->user->id];
            $list = AddressModel::getList($map, false, 'create_time', ['p', 'c', 'd']);
            return Result::success('获取成功', $list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 修改添加
     */
    public function save(): Json
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Address');
            return Result::fastReturn(AddressModel::add($param, $this->user));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 地址详情
     */
    public function details(): Json
    {
        try {
            $id = $this->request->get('id');
            $info = AddressModel::where('id', $id)->with(['p', 'c', 'd'])->find();
            if (!$info) {
                return Result::fail('数据不存在！');
            }
            return Result::success('获取成功！', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 地址操作
     * @return Json
     */
    public function edit(): Json
    {
        $param = $this->request->post();
        try {
            $type = $param['type'];
            switch ($type) {
                case 'del':
                    return Result::fastReturn(AddressModel::edit($this->request->post('id'), $this->user));
                    break;
                case 'default':
                    AddressModel::update(['default' => 0], ['uid' => $this->user->id]);
                    AddressModel::update(['default' => 1], ['id' => $param['id']]);
                    return Result::success('设置成功');
                    break;
                default:
                    return Result::fail('参数错误');
            }
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 省市区联动
     */
    public function getArea($id, $level = 0)
    {
        try {
            return Result::success('获取成功', Area::getArea($id ?: 0, $level));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
